//
//  PageView.m
//  ebook
//
//  Created by 吴超飞 on 16/1/15.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "PageView.h"
#import <CoreText/CoreText.h>

@implementation PageView

- (void)setText:(NSAttributedString *)attributedText
{
    self.attributedText = attributedText;
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
   
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    
    //绘制之前先清空
    CGContextClearRect(context,rect);
    
    NSMutableAttributedString* attrStrWithLinks = [self.attributedText mutableCopy];
    CTFramesetterRef childFramesetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attrStrWithLinks);
    UIBezierPath * bezierPath = [UIBezierPath bezierPathWithRect:rect];
    CTFrameRef frame = CTFramesetterCreateFrame(childFramesetter, CFRangeMake(0, 0), bezierPath.CGPath, NULL);
    CTFrameDraw(frame, context);
    
    if(frame)
        CFRelease(frame);
    
    if(childFramesetter)
        CFRelease(childFramesetter);
}

-(void)dealloc{
    self.attributedText = nil;
    [self removeFromSuperview];
}

@end
